package com.rule;

import java.util.List;
import java.util.Random;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

public class MySelfRule2 extends AbstractLoadBalancerRule {
	
	// 修改为每个服务必须调用5次才能换下一个服务
	private int TOTAL = 0;
	private int CURRENT_SIZE = 0;
	
	Random rand;

	public MySelfRule2() {
        rand = new Random();
    }

	/**
	 * Randomly choose from all living servers
	 */
	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;
		
		// 多线程用 while 
		while (server == null) {
			
			// 判断是否中断
			if (Thread.interrupted()) {
				return null;
			}
			
			// 获取所有可用服务或者可达成的服务
			List<Server> upList = lb.getReachableServers();
			List<Server> allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				/*
				 * No servers. End regardless of pass, because subsequent passes
				 * only get more restrictive.
				 */
				return null;
			}
			// 调用rand 方法
			if(TOTAL < 5){
				TOTAL++;
			} else {
				TOTAL = 0;
				CURRENT_SIZE++;
				if(CURRENT_SIZE >= upList.size()){
					CURRENT_SIZE = 0;
				}
			}
			// 获取当前服务
			server = upList.get(CURRENT_SIZE);
			if (server == null) {
				/*
				 * The only time this should happen is if the server list were
				 * somehow trimmed. This is a transient condition. Retry after
				 * yielding.
				 */
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}

			// Shouldn't actually happen.. but must be transient or a bug.
			server = null;
			Thread.yield();
		}

		return server;

	}

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub

	}

}
